package com.peaksport.framework.util;

import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.peaksport.framework.exception.PKBizException;

public class PKJSONUtils {
	
	 /** fastxml jackson 的json处理对象*/
    private static ObjectMapper jsonObjMapper = new ObjectMapper();
    /**
	 * 自定义序列化格式:
	 *  1. 日期格式统一为 yyyy-MM-dd HH:mm:ss 如: 2019-01-25 18:03:30
	 *  2. 仅序列化非空not-null的对象
	 *  
	 *  PS:序列化自定义格式尽量与PKRestObjectMapper保持一致
     */
    static {
        jsonObjMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        jsonObjMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES,true);
        //日期格式
        jsonObjMapper.setDateFormat(PKPublicUtils.SDF_YYYYMMDD_HHMMSS);
        //序列化非空not-null的对象
        jsonObjMapper.setSerializationInclusion(Include.NON_NULL);
    }
	
    /**
     * 将对象转换成json字串
     * 
     * @param obj
     * @param prettyPrinter 是否美化格式化
     * @return
     */
    public static String toJSON(Object obj, boolean prettyPrinter) {
    	try {
			String json = null;
			if (prettyPrinter) json = jsonObjMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
			else json = jsonObjMapper.writeValueAsString(obj);
			return json;
		} catch (Exception e) {
			String msg = e.getMessage();
			throw PKBizException.throwException("对象[%s]转JSON格式异常: %s",obj.getClass().getName(), msg);
		}
    	
    }
    /**
     * 将对象转换成json字串
     * 默认不美化json字串
     * @param obj
     * @return
     */
	public static String toJSON(Object obj) {
		return toJSON(obj,false);
	}
	
	public static Object toBean(byte[] bytes, Class clazz) {
		try {
			return jsonObjMapper.readValue(bytes, clazz);
		} catch (Exception e) {
			String msg = e.getMessage();
			throw PKBizException.throwException("JSON子串转对象[%s]异常",clazz.getName());

		}
	}
	public static Object toBean(String json, Class clazz) {
		return toBean(json.getBytes(),clazz);
	}
}
